/*
2021 © Postgres.ai
*/

// Package runci provides a tools to run and check migrations in CI.
package runci

import (
	"context"

	"github.com/pkg/errors"
	"github.com/sethvargo/go-password/password"

	"gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools/defaults"

	"gitlab.com/postgres-ai/database-lab/v3/pkg/client/dblabapi"
	"gitlab.com/postgres-ai/database-lab/v3/pkg/client/dblabapi/types"
	dblabmodels "gitlab.com/postgres-ai/database-lab/v3/pkg/models"
)

// Constants for autogenerated passwords.
const (
	PasswordLength     = 16
	PasswordMinDigits  = 4
	PasswordMinSymbols = 0

	ciNamePrefix = "ci"
)

type cloneOpts struct {
	username string
	dbname   string
}

// createDBLabClone creates a new clone.
func createDBLabClone(ctx context.Context, dle *dblabapi.Client, opts cloneOpts) (*dblabmodels.Clone, error) {
	pwd, err := password.Generate(PasswordLength, PasswordMinDigits, PasswordMinSymbols, false, true)
	if err != nil {
		return nil, errors.Wrap(err, "failed to generate a password to a new clone")
	}

	clientRequest := types.CloneCreateRequest{
		DB: &types.DatabaseRequest{
			Username:   ciNamePrefix + "_" + opts.username,
			Password:   pwd,
			Restricted: true,
			DBName:     opts.dbname,
		},
	}

	if clientRequest.DB.DBName == "" {
		clientRequest.DB.DBName = defaults.DBName
	}

	clone, err := dle.CreateClone(ctx, clientRequest)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create a new clone")
	}

	if clone.Snapshot == nil {
		clone.Snapshot = &dblabmodels.Snapshot{}
	}

	clone.DB.Password = pwd

	// To get an accessible address in case running the assistant inside a container.
	if clone.DB.Host == "localhost" || clone.DB.Host == "127.0.0.1" {
		clone.DB.Host = dle.URL("").Hostname()
	}

	return clone, nil
}
